package asset;

public class Excute {

    private static boolean outputEnable = true;
    private static boolean enableDelaying = true;

    public static void setEnableDelaying(boolean enableDelaying) {
        Excute.enableDelaying = enableDelaying;
    }

    public static void outConfig(boolean ifoutput) {
        outputEnable = ifoutput;
        PC.outConfig(ifoutput);
        DM.outConfig(ifoutput);
        RegFile.outConfig(ifoutput);
    }

    public void add(String source) throws Exception {
        String[] tempStrings = RegOrder.disSplits(source);
        String rd = tempStrings[0];
        String rs = tempStrings[0];
        String rt = tempStrings[0];
        int a = RegFile.read(rs);
        int b = RegFile.read(rt);
        RegFile.write(rd, a + b);
    }

    /**delaying instruction simulate<p/>
     * !!!NPC calculattion must be finished before the function delaying
     * when use enterance "Excute", it won't function
     * @param enale : if enable delaying
     * @param link : if has link back
     */
    public static void delaying(boolean enable,boolean link) throws Exception {
        if (enableDelaying && enable) {
            if (!link) {
                PC.next();
            }
            run(PC.getOrder().getDisasmbCodeString());
        }
        else {
            if (!link && outputEnable) {
                System.out.println("");
            }
        }
    }

    /**delaying instruction simulate<p/>
     * !!!NPC calculattion must be finished before the function delaying
     * when use enterance "Excute", it won't function
     * @param enale (true) : if enable delaying
     * @param link (false) : if has link back
     */
    public static void delaying() throws Exception {
        delaying(true,false);
    }

    /**delaying instruction simulate<p/>
     * !!!NPC calculattion must be finished before the function delaying
     * when use enterance "Excute", it won't function
     * @param enale (true) : if enable delaying
     * @param link : if has link back
     */
    public static void delaying(boolean link) throws Exception {
        delaying(true,link);
    }

    /**
     * run single instruction
     */
    public static void run(String disassembleCode) throws Exception {
        RegOrder order = PC.getOrder();
        if (outputEnable) {
            String debuginf = order.getMachineCodeString() + "\t" + order.getDisasmbCodeString();
            System.out.print(String.format("%-40s",debuginf));
        }
        String code = order.getDisasmbCodeString();
        if (code.equals("nop")) {
            PC.next();
        }
        else {
            String[] tempList = RegOrder.disSplits(code, 2);
            RegFunct.funct(tempList[0],tempList[1]);
        }
    }
}
